import { computed, ref, watchEffect } from 'vue'
import { analyseResultGetService } from '@/api/enterprise'
import {
  createKnowledgeBaseService,
  getBaseListService,
  getDocsListService,
  deleteDocsService,
  baseChatService,
  ChatService,
  uploadDocsService
} from '@/api/chat'
//获取知识库中没有的简历分析结果列表
let result_obj = ref([])
// let base_name = 'keqingcuteBase'
const getNewResult = async (base_name) => {
  // AnalyseResultList部分
  const analyseResultData = await analyseResultGetService()
  const resultList = analyseResultData.data.data
  const resultId = resultList.map((item) => item.informationId)

  // DocsList部分
  const docsData = await getDocsListService(base_name)
  const docsList = docsData.data.data
  const docstId = docsList.map((item) => parseInt(item.split('_')[0], 10))

  // 使用 filter 方法筛选出 在resultI 中不在 docs 中的元素
  let notIn = resultId.filter((item) => !docstId.includes(item))
  if (notIn.length === 0) {
    // console.log('没有元素在在resultI中但不在docs中')
    return 'notNew' //终止方法
  }
  // else {
  //   console.log(notIn)
  //   console.log(notIn.length)
  // }
  // 将notIn转换为一个Set以优化查找性能
  const notInSet = new Set(notIn)
  // 使用for...of循环遍历num2数组
  for (const item of resultList) {
    // 检查item的informationId是否存在于num1Set中
    if (notInSet.has(item.informationId)) {
      // 如果存在
      result_obj.value.push(item)
      // console.log(item)
    }
  }
  return
}
//处理为可提交文本
const textList = computed(() => {
  if (result_obj.value === null) {
    return
  }
  const data = result_obj.value
  return data.map((item) => {
    const str = JSON.parse(item.analyseResult)
    const text = str.result.raw_text
    const realName = item.name || 'default_name' // 当name为null或undefined时
    const id = item.informationId
    //text,蚊子识别的简历内容 ,realName，用户所完善的姓名, id，简历ID
    return { text, realName, id }
  })
})
//上传
const updateDocs = async (base_name) => {
  if (!base_name) {
    throw new Error('base_name is required')
  }
  // 使用 watchEffect 来监听 textList 的变化
  watchEffect(async () => {
    // 确保 result_obj 是最新的
    const flag = await getNewResult(base_name)
    if (flag === 'notNew') {
      ElMessage({ type: 'success', message: '知识库无需更新' })
      return
    }
    const DOCS_formData = new FormData()

    // 遍历 textList 数组并构建 FormData
    for (const { text, realName, id } of textList.value) {
      const blob = new Blob([text], { type: 'text/plain' })
      const file = new File([blob], `${id}_${realName}.txt`, {
        type: 'text/plain'
      })
      DOCS_formData.append('files', file)
    }
    // 添加其他必要字段
    DOCS_formData.append('knowledge_base_name', base_name)
    // 执行上传服务
    try {
      // // 检查 打印 FormData 的内容
      // for (const [key, value] of DOCS_formData.entries()) {
      //   console.log(`${key}: ${value}`)
      // }
      await uploadDocsService(DOCS_formData)
      ElMessage({ type: 'success', message: '知识库更新成功！' })
    } catch (error) {
      ElMessage({ type: 'error', message: '知识库更新失败！' })
    }
  })
}

/*创建知识库*/
const createBase = (base_name) => {
  createKnowledgeBaseService(base_name)
}
/*获取知识库列表*/
const getBaseList = async () => {
  const res = await getBaseListService()
  //增加过滤
  return res.data.data
}
/*获取知识库内文件列表*/
const getDocsList = async (base_name) => {
  const res = await getDocsListService(base_name)
  let filenames = res.data.data
  //数字排序
  filenames.sort(function (a, b) {
    // 提取文件名中的数字部分
    var numA = parseInt(a.split('_')[0], 10)
    var numB = parseInt(b.split('_')[0], 10)
    // 比较数字大小
    return numA - numB
  })
  return filenames
}
/*删除知识库文件*/
const deleteDocs = async (base_name, files) => {
  const res = await deleteDocsService(base_name, files)
  return res.msg
}
/*chat*/
const chatAI = async (query, mode, base_name) => {
  let res = null
  if (mode === 'Chat对话') {
    //chatAI
    try {
      res = await ChatService(query)
    } catch (error) {
      return '网络错误，请稍后重试'
    }
  } else {
    //chatBase
    try {
      res = await baseChatService(query, base_name)
    } catch (error) {
      return '网络错误，请稍后重试'
    }
  }
  let answer = res.data
  try {
    answer = answer.substring(answer.indexOf('{'))
    answer = JSON.parse(answer)
  } catch (error) {
    // 这里处理错误
    console.error('发生错误:', error)
    // 你可以根据需要重新抛出错误或进行其他处理
    return '发生错误,可能您未选正确择知识库'
    // throw error;
  }
  if (mode === 'Chat对话') {
    return answer.text
  } else {
    return answer.answer
  }
}

export default {
  createBase,
  getBaseList,
  getDocsList,
  deleteDocs,
  chatAI,
  updateDocs
}
